<template>
  <div class="attendance-rule-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">考勤规则管理</span>
          <div class="right-button">
            <el-button type="primary" icon="Plus" @click="handleAdd">
              新增规则
            </el-button>
            <el-button icon="Download" @click="handleExport"> 导出 </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input
            v-model="queryParams.ruleName"
            placeholder="请输入规则名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="规则状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="ruleList" style="width: 100%" border>
        <el-table-column
          prop="ruleId"
          label="规则ID"
          align="center"
          width="80"
        />
        <el-table-column
          prop="ruleName"
          label="规则名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="workDays"
          label="工作日"
          align="center"
          width="150"
        >
          <template #default="scope">
            {{ formatWorkDays(scope.row.workDays) }}
          </template>
        </el-table-column>
        <el-table-column label="工作时间" align="center" width="200">
          <template #default="scope">
            {{ scope.row.workStartTime }} - {{ scope.row.workEndTime }}
          </template>
        </el-table-column>
        <el-table-column label="午休时间" align="center" width="200">
          <template #default="scope">
            <span v-if="scope.row.restStartTime && scope.row.restEndTime">
              {{ scope.row.restStartTime }} - {{ scope.row.restEndTime }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              icon="Edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              link
              icon="View"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              size="small"
              type="danger"
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="750px"
      append-to-body
    >
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>

        <el-form-item label="工作日" prop="workDays">
          <el-checkbox-group v-model="workDaysSelected">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="7">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="工作时间" required>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="workStartTime">
                <el-time-picker
                  v-model="form.workStartTime"
                  placeholder="上班时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="workEndTime">
                <el-time-picker
                  v-model="form.workEndTime"
                  placeholder="下班时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="午休时间">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="restStartTime">
                <el-time-picker
                  v-model="form.restStartTime"
                  placeholder="午休开始时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="restEndTime">
                <el-time-picker
                  v-model="form.restEndTime"
                  placeholder="午休结束时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="打卡时间">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="最早签到时间"
                label-width="100px"
                prop="earliestCheckInTime"
              >
                <el-time-picker
                  v-model="form.earliestCheckInTime"
                  placeholder="最早签到时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="最晚签到时间"
                label-width="100px"
                prop="latestCheckInTime"
              >
                <el-time-picker
                  v-model="form.latestCheckInTime"
                  placeholder="最晚签到时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="最早签退时间"
                label-width="100px"
                prop="earliestCheckOutTime"
              >
                <el-time-picker
                  v-model="form.earliestCheckOutTime"
                  placeholder="最早签退时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="最晚签退时间"
                label-width="100px"
                prop="latestCheckOutTime"
              >
                <el-time-picker
                  v-model="form.latestCheckOutTime"
                  placeholder="最晚签退时间"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="规则配置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="是否允许加班"
                label-width="100px"
                prop="allowOvertime"
              >
                <el-radio-group v-model="form.allowOvertime">
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="加班需审批"
                label-width="100px"
                prop="overtimeNeedsApproval"
              >
                <el-radio-group
                  v-model="form.overtimeNeedsApproval"
                  :disabled="form.allowOvertime === '1'"
                >
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="是否允许请假"
                label-width="100px"
                prop="allowLeave"
              >
                <el-radio-group v-model="form.allowLeave">
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="请假需审批"
                label-width="100px"
                prop="leaveNeedsApproval"
              >
                <el-radio-group
                  v-model="form.leaveNeedsApproval"
                  :disabled="form.allowLeave === '1'"
                >
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="规则描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入规则描述"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  getAttendanceRuleList,
  getAttendanceRuleInfo,
  addAttendanceRule,
  updateAttendanceRule,
  deleteAttendanceRule,
  exportAttendanceRule,
  changeAttendanceRuleStatus
} from "@/api/attendance/attendance-rule";
import {
  AttendanceRule,
  AttendanceRuleQuery
} from "@/api/attendance/types/attendance-rule";
import {
  handleApiError,
  handleLoadError,
  handleFormError
} from "@/utils/error-handler";

// 状态选项
const statusOptions = [
  { value: "0", label: "正常" },
  { value: "1", label: "停用" }
];

// 查询参数
const queryParams = reactive<AttendanceRuleQuery>({
  ruleName: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 表格数据
const ruleList = ref<AttendanceRule[]>([]);
const loading = ref(false);
const total = ref(0);

// 对话框属性
const dialog = reactive({
  title: "",
  visible: false
});

// 表单数据
const form = reactive<AttendanceRule>({
  ruleName: "",
  workDays: "",
  workStartTime: "",
  workEndTime: "",
  restStartTime: "",
  restEndTime: "",
  earliestCheckInTime: "",
  latestCheckInTime: "",
  earliestCheckOutTime: "",
  latestCheckOutTime: "",
  allowOvertime: "0",
  overtimeNeedsApproval: "0",
  allowLeave: "0",
  leaveNeedsApproval: "0",
  status: "0",
  description: "",
  remark: ""
});

// 选中的工作日
const workDaysSelected = ref<string[]>([]);

// 监听工作日选择变化，更新表单中的工作日字段
watch(
  workDaysSelected,
  val => {
    form.workDays = val.sort().join(",");
  },
  { deep: true }
);

// 反向监听表单中的工作日字段变化，更新选中的工作日
watch(
  () => form.workDays,
  val => {
    if (val) {
      workDaysSelected.value = val.split(",");
    } else {
      workDaysSelected.value = [];
    }
  },
  { immediate: true }
);

// 格式化工作日显示
const formatWorkDays = (workDays: string) => {
  if (!workDays) return "-";

  const dayNames: { [key: string]: string } = {
    "1": "周一",
    "2": "周二",
    "3": "周三",
    "4": "周四",
    "5": "周五",
    "6": "周六",
    "7": "周日"
  };

  return workDays
    .split(",")
    .map(day => dayNames[day] || day)
    .join(", ");
};

// 表单校验规则
const rules = reactive<FormRules>({
  ruleName: [
    { required: true, message: "请输入规则名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "规则名称长度在2到50个字符之间",
      trigger: "blur"
    }
  ],
  workDays: [{ required: true, message: "请选择工作日", trigger: "change" }],
  workStartTime: [
    { required: true, message: "请选择上班时间", trigger: "change" }
  ],
  workEndTime: [
    { required: true, message: "请选择下班时间", trigger: "change" }
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
});

// 表单引用
const queryRef = ref<FormInstance>();
const ruleForm = ref<FormInstance>();

// 获取考勤规则列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getAttendanceRuleList(queryParams);
    ruleList.value = res.data.rows || [];
    total.value = res.data.total || 0;
  } catch (error) {
    handleLoadError(error, "考勤规则列表");
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields();
  }
  handleQuery();
};

// 分页操作
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getList();
};

// 页码操作
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getList();
};

// 状态修改操作
const handleStatusChange = async (row: AttendanceRule) => {
  try {
    await changeAttendanceRuleStatus(row.ruleId as string, row.status);
    ElMessage.success(`规则${row.status === "0" ? "启用" : "停用"}成功`);
  } catch (error) {
    // 恢复原始状态
    row.status = row.status === "0" ? "1" : "0";
    handleApiError(error, "修改规则状态失败");
  }
};

// 新增按钮操作
const handleAdd = () => {
  dialog.title = "添加考勤规则";
  dialog.visible = true;
  resetForm();
};

// 编辑按钮操作
const handleUpdate = async (row: AttendanceRule) => {
  dialog.title = "修改考勤规则";
  dialog.visible = true;
  resetForm();

  try {
    const res = await getAttendanceRuleInfo(row.ruleId as string);
    Object.assign(form, res.data);
  } catch (error) {
    handleLoadError(error, "考勤规则详情");
  }
};

// 查看按钮操作
const handleView = async (row: AttendanceRule) => {
  try {
    const res = await getAttendanceRuleInfo(row.ruleId as string);
    const ruleData = res.data;

    ElMessageBox.alert(
      `<div style="margin-bottom: 10px;"><strong>规则名称：</strong>${
        ruleData.ruleName
      }</div>
       <div style="margin-bottom: 10px;"><strong>工作日：</strong>${formatWorkDays(
         ruleData.workDays
       )}</div>
       <div style="margin-bottom: 10px;"><strong>工作时间：</strong>${
         ruleData.workStartTime
       } - ${ruleData.workEndTime}</div>
       <div style="margin-bottom: 10px;"><strong>午休时间：</strong>${
         ruleData.restStartTime && ruleData.restEndTime
           ? `${ruleData.restStartTime} - ${ruleData.restEndTime}`
           : "-"
       }</div>
       <div style="margin-bottom: 10px;"><strong>最早签到时间：</strong>${
         ruleData.earliestCheckInTime || "-"
       }</div>
       <div style="margin-bottom: 10px;"><strong>最晚签到时间：</strong>${
         ruleData.latestCheckInTime || "-"
       }</div>
       <div style="margin-bottom: 10px;"><strong>最早签退时间：</strong>${
         ruleData.earliestCheckOutTime || "-"
       }</div>
       <div style="margin-bottom: 10px;"><strong>最晚签退时间：</strong>${
         ruleData.latestCheckOutTime || "-"
       }</div>
       <div style="margin-bottom: 10px;"><strong>是否允许加班：</strong>${
         ruleData.allowOvertime === "0" ? "是" : "否"
       }</div>
       <div style="margin-bottom: 10px;"><strong>加班需审批：</strong>${
         ruleData.overtimeNeedsApproval === "0" ? "是" : "否"
       }</div>
       <div style="margin-bottom: 10px;"><strong>是否允许请假：</strong>${
         ruleData.allowLeave === "0" ? "是" : "否"
       }</div>
       <div style="margin-bottom: 10px;"><strong>请假需审批：</strong>${
         ruleData.leaveNeedsApproval === "0" ? "是" : "否"
       }</div>
       <div style="margin-bottom: 10px;"><strong>规则状态：</strong>${
         ruleData.status === "0" ? "正常" : "停用"
       }</div>
       <div style="margin-bottom: 10px;"><strong>规则描述：</strong>${
         ruleData.description || "-"
       }</div>
       <div><strong>备注：</strong>${ruleData.remark || "-"}</div>`,
      "考勤规则详情",
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定"
      }
    );
  } catch (error) {
    handleLoadError(error, "考勤规则详情");
  }
};

// 删除按钮操作
const handleDelete = (row: AttendanceRule) => {
  ElMessageBox.confirm(`是否确认删除考勤规则"${row.ruleName}"?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteAttendanceRule(row.ruleId as string);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        handleApiError(error, "删除考勤规则失败");
      }
    })
    .catch(() => {});
};

// 导出按钮操作
const handleExport = () => {
  exportAttendanceRule(queryParams);
};

// 重置表单
const resetForm = () => {
  form.ruleId = undefined;
  form.ruleName = "";
  form.workDays = "1,2,3,4,5";
  form.workStartTime = "09:00:00";
  form.workEndTime = "18:00:00";
  form.restStartTime = "12:00:00";
  form.restEndTime = "13:00:00";
  form.earliestCheckInTime = "07:00:00";
  form.latestCheckInTime = "09:30:00";
  form.earliestCheckOutTime = "17:30:00";
  form.latestCheckOutTime = "21:00:00";
  form.allowOvertime = "0";
  form.overtimeNeedsApproval = "0";
  form.allowLeave = "0";
  form.leaveNeedsApproval = "0";
  form.status = "0";
  form.description = "";
  form.remark = "";

  if (ruleForm.value) {
    ruleForm.value.resetFields();
  }
};

// 提交表单
const submitForm = async () => {
  if (!ruleForm.value) return;

  await ruleForm.value.validate(async valid => {
    if (!valid) return;

    try {
      if (form.ruleId) {
        // 更新
        await updateAttendanceRule(form);
        ElMessage.success("修改成功");
      } else {
        // 新增
        await addAttendanceRule(form);
        ElMessage.success("新增成功");
      }
      dialog.visible = false;
      getList();
    } catch (error) {
      handleFormError(error, "考勤规则");
    }
  });
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.attendance-rule-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 18px;
        font-weight: bold;
      }

      .right-button {
        display: flex;
        gap: 10px;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
